package trab_sd;

import java.util.*;
import java.net.*;
import java.io.*;

public class FileListReceiver implements Runnable {
	
	private User localUser;
	private Socket connection;
	private ObjectInputStream in;
	private ObjectOutputStream out;
	private boolean cont;
	private int i = 0;
	
	public FileListReceiver ( User localUser, Socket connection, ObjectOutputStream out, ObjectInputStream in ) {
		//recebe o usuario local e a conexao
		this.localUser = localUser;
		this.connection = connection;
		this.out = out;
		this.in = in;
		cont = connection.isConnected();
	}
	
	public void run() {
		try {
			if (cont == false) return;
			//Envia mensagem indicando que esta preparado para receber a lista
			out.writeUTF("OK");
			out.flush();
			
			//Recebe a lista
			FileList tmpFL = (FileList) in.readObject();
			
			//Espera mensagem indicando o fim da transacao
			if ( !in.readUTF().equals("FINISHED")  ) throw new SocketTimeoutException();
			
			//Atualiza a lista de arquivos local
			localUser.updateFileList(tmpFL);

			//Se for servidor manda pra todo mundo
			if ( localUser.isServer() ) {
				localUser.sendUserListToAll();
				localUser.sendFileListToAll();
				localUser.setCont(true);
			}
			
			//atualiza a lista local
			localUser.updateFileList(tmpFL);
		}
		catch ( ConnectException ce ) {
			ce.printStackTrace();
		}
		catch ( IOException ioe ) {
			ioe.printStackTrace();
		}
		catch ( ClassNotFoundException cnfe ) {
			cnfe.printStackTrace();
		}
		finally {
			try {
				//fecha os streams
				in.close();
				out.close();
				
				//fecha a conexao
				connection.close();
			}
			catch ( NullPointerException npe ) {
				if ( i < 3 ) {
					i++;
					run();
				}
				else {
					npe.printStackTrace();
				}
			}
			catch (Exception e) {
				e.printStackTrace();
			}
			return;
		}
	}
}